<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Admin extends MY_Admin_Controller {

	private $data;
	private $menu_array;

    public $fields;            /** columns names retrieved after parsing */ 
    public $separator = ',';    /** separator used to explode each line */
    public $enclosure = '"';    /** enclosure used to decorate each field */
    
    public $max_row_size = 4096;    /** maximum row size to be used for decoding */
    
    private $crud;

	function __construct() {
		parent::__construct();

		$this->load->library('csv_reader');
		$this->load->library('grocery_CRUD');
		$this->crud = new grocery_CRUD();
		$this->crud->set_theme('flexigrid');
		$this->crud->set_language($this->config->item('language'));
		
	}

	public function login()
	{
		$this->_handle_if_post('admin_login');

		$this->load->view('admin/login',$this->data);
	}

	function _example_output($output = null) {
		$this->load->view('admin/admin.php', $output);
	}

	function index() {
		$this->_example_output((object) array('output' => '', 'js_files' => array('1' => ASSETS_URL . 'grocery_crud/js/jquery-1.7.1.min.js'), 'css_files' => array()));
	}
	
	public function language_manage() {
		//check access, only admin
		$this->access->Allow(ADMIN);
		
		$this->crud->set_table('languages');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('key', lang('language_key'));
		$this->crud->display_as('name', lang('language_name'));
		$this->crud->set_subject(lang('languages'));	
			
		$this->crud->columns('id', 'key', 'name');
   		$this->crud->add_fields('key', 'name');
    	$this->crud->edit_fields('key', 'name');		


		$output = $this->crud->render();

		$this->_example_output($output);
	}
	
	public function content_manage() {
		//check access, only admin
		$this->access->Allow(ADMIN);
				
		$this->crud->set_table('lang_general');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('key', lang('content_key'));
		$this->crud->display_as('en', lang('content_en'));
		$this->crud->display_as('ro', lang('content_ro'));
		$this->crud->display_as('it', lang('content_it'));
		$this->crud->display_as('fr', lang('content_fr'));
		$this->crud->display_as('de', lang('content_de'));
		$this->crud->display_as('sv', lang('content_sv'));
		$this->crud->display_as('es', lang('content_es'));
		$this->crud->display_as('sk', lang('content_sk'));
		$this->crud->display_as('pt', lang('content_pt'));
		$this->crud->display_as('hu', lang('content_hu'));
		$this->crud->display_as('fi', lang('content_fi'));
		$this->crud->display_as('cz', lang('content_cz'));
		
		$this->crud->set_subject(lang('content'));	
		
		$this->crud->columns('key', 'en');
			
		$output = $this->crud->render();

		$this->_example_output($output);
	}	
	
	public function site_config() {
		//check access, only admin
		$this->access->Allow(ADMIN);
				
		$this->crud->set_table('site_config');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('last_updated', lang('last_updated'));
		$this->crud->display_as('config_key', lang('config_key'));
		$this->crud->display_as('config_value', lang('config_value'));
		$this->crud->set_subject(lang('site_config'));	
		
		$this->crud->columns('id', 'last_updated', 'config_key', 'config_value');
   		$this->crud->add_fields('config_key', 'config_value');
    	$this->crud->edit_fields('config_key', 'config_value');		
			
		$output = $this->crud->render();

		$this->_example_output($output);
	}

	public function site_management() {
		//check access, only admin
		$this->access->Allow(ADMIN);

		$error = '';
		$successs = false;
		if ($this->input->post('upload')) {
			$config['upload_path'] = './datafeed/';
			$config['allowed_types'] = 'csv';
			$config['overwrite'] = TRUE;
	
			$this->load->library('upload', $config);
	
			if ( ! $this->upload->do_upload())
			{
				$error = $this->upload->display_errors();
			}
			else
			{
				$successs = true;
			}
		}
		
		$this->crud->set_table('logs');
		$this->crud->display_as('user_id', lang('user_id'));
		$this->crud->display_as('datetime', lang('datetime'));
				
    	$this->crud->unset_add();
        $this->crud->unset_edit();
        $this->crud->unset_delete();
		$this->crud->set_subject(lang('site_management'));	
		$this->crud->set_relation('user_id', 'users', 'user_email');
		
		//$this->crud->columns('id', 'user_id', 'datetime');        

		$output = $this->crud->render();
		$output->output .= '<br />';
		$output->output .= form_open_multipart('admin/site_management');
		if (strlen($error)) {
			$output->output .= '<div class="error">' . $error . '</div>';
		}
		elseif($successs) {
			$output->output .= '<div class="success"><p>' . lang('upload_success') . '</p></div>';
		}
		$output->output .= '
			<label for="userfile">' . lang('CSV files') . '</label>
			<input type="file" id="userfile" name="userfile" size="20" />
			
			<br /><br />
			
			<input name="upload" type="submit" value="' . lang('upload') . '" />
			
			</form>';
		$output->output .= '<br />';
		$output->output .=  anchor('import/start', lang('start_sync'), 'target="_blank"') . ' (' . lang('if_you_startit_wait_till_end') . ')';
		$output->output .= '<br />' .  anchor('cache/clear', lang('clear_cache'), 'target="_blank"') . ' (' . lang('after_sync_recomended') . ')';
		$this->_example_output($output);
	}
	
	public function curier_management() {
		//check access, only admin
		$this->access->Allow(ADMIN);
				
		$this->crud->set_table('curier');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('name', lang('curier_name'));
		$this->crud->display_as('tax', lang('curier_tax'));
		$this->crud->display_as('web_page', lang('web_page'));
		$this->crud->set_subject(lang('curier'));	
		
		$this->crud->columns('id', 'name', 'tax', 'web_page');
   		$this->crud->add_fields('name', 'web_page');
    	$this->crud->edit_fields('name', 'tax', 'web_page');	
    		
		$output = $this->crud->render();

		$this->_example_output($output);
	}	

	public function ask_jeweler_management() {
		//check access, only admin
		//$this->access->Allow(ADMIN);
				
		$this->crud->set_table('questions');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('question', lang('question'));
		$this->crud->display_as('answer', lang('answer'));
		$this->crud->display_as('published', lang('published'));
		$this->crud->display_as('product_id', lang('product_sku'));
		
		if (!$this->access->isRole(ADMIN)) {
			$this->crud->where('questions.language_id', $this->access->getUserLang());
		}
		
		$this->crud->set_subject(lang('ask_jeweler'));	
		
		$this->crud->set_relation('product_id','products','sku');
		
		$this->crud->change_field_type('published', 'true_false');
		$this->crud->change_field_type('question', 'readonly');
		$this->crud->change_field_type('answered_by', 'hidden', $this->access->getUserId());
		
		$this->crud->columns('id', 'question', 'published');
		$this->crud->unset_columns('product_id','answer','user_id');
   		$this->crud->unset_add();
    	$this->crud->edit_fields('question', 'answer', 'published','answered_by');		
			
		$output = $this->crud->render();

		$this->_example_output($output);
	}

	function user_manager() {
		//check access, only admin
		$this->access->Allow(ADMIN);
				
		$this->crud->set_table('users');
		$this->crud->display_as('type_id', lang('user_type'));
		$this->crud->display_as('language_id', lang('language_id'));
		$this->crud->display_as('user_email', lang('user_email'));
		$this->crud->display_as('user_name', lang('user_name'));
		$this->crud->display_as('description', lang('user_description'));
		$this->crud->display_as('profile_pic', lang('profile_pic'));

		$this->crud->set_subject(lang('user'));
		$this->crud->required_fields('user_email','user_pass');	
		$this->crud->set_rules('user_email',lang('user_email'),'valid_email|required');

		$this->crud->set_relation('type_id','user_type','type_name');
		$this->crud->set_relation('language_id','languages','name');
			
		$this->crud->columns('id', 'user_email', 'user_date', 'type_id', 'language_id', 'user_name','description', 'discount_code');
		$this->crud->add_fields('user_email', 'user_pass', 'type_id', 'language_id', 'user_name','description','profile_pic', 'discount_code');
    	$this->crud->edit_fields('id','user_email', 'user_pass', 'type_id', 'language_id', 'user_name','description','profile_pic', 'discount_code');	
    	
	    $this->crud->callback_edit_field('id',array($this,'set_disabled_input'));
	    $this->crud->callback_add_field('user_pass',array($this,'set_password_input_to_empty'));    	
		
		$this->crud->callback_update(array($this,'encrypt_password_and_update'));
		$this->crud->callback_insert(array($this,'encrypt_password_and_insert_callback'));
		
		$this->crud->set_field_upload('profile_pic', IMAGES_PATH . 'user_pics/');

		$output = $this->crud->render();

		$this->_example_output($output);
	}
	
	function frontend_user_manager() {
		//check access, only admin
		$this->access->Allow(ADMIN);
	
		$this->crud->set_table('fe_users');
		$this->crud->display_as('language_id', lang('language_id'));
		$this->crud->display_as('user_email', lang('user_email'));
		$this->crud->display_as('first_name', lang('first_name'));
		$this->crud->display_as('last_name', lang('last_name'));
		$this->crud->display_as('discount_code', lang('discount_code'));
	
		$this->crud->set_subject(lang('user'));
		$this->crud->required_fields('user_email','user_pass');
		$this->crud->set_rules('user_email',lang('user_email'),'valid_email|required');
			
		$this->crud->columns('id', 'user_email', 'first_name', 'last_name', 'discount_code');
		$this->crud->edit_fields('id','user_email', 'first_name', 'last_name', 'discount_code');
		$this->crud->unset_add();
		
		$output = $this->crud->render();
	
		$this->_example_output($output);
	}
	
	function newsLetter() {
		//check access, only admin
		//$this->access->Allow(ADMIN);
	
		$this->crud->set_table('fe_users');
		$this->crud->display_as('language_id', lang('language_id'));
		$this->crud->display_as('user_email', lang('user_email'));
			
		$this->crud->set_subject(lang('user'));
		$this->crud->set_rules('user_email',lang('user_email'),'valid_email|required');
			
		$this->crud->columns('id', 'user_email');
		$this->crud->unset_edit();
		$this->crud->unset_delete();

		$output = $this->crud->render();
	
		$this->_example_output($output);
	}
	
	public function encrypt_password_and_update($post_array, $primary_key) {
	    $this->load->model('user_model');
	    $existingData = $this->user_model->get_by_id($primary_key);
		if ($existingData->user_pass != $post_array['user_pass']) {
			$hasher = new PasswordHash(8, false);    
		    $post_array['user_pass'] = (isset($post_array['user_pass']) && !empty($post_array['user_pass'])) ? $hasher->HashPassword($post_array['user_pass']) : '';
		}
	 	$post_array['user_modified'] = date('Y-m-d h:i:s');
	 	
	  	return $this->db->update('users',$post_array,array('id' => $primary_key));
	}	
	
	public function encrypt_password_and_insert_callback($post_array) {
		$hasher = new PasswordHash(8, false); 
		$post_array['user_pass'] = (isset($post_array['user_pass']) && !empty($post_array['user_pass'])) ? $hasher->HashPassword($post_array['user_pass']) : '';
		$post_array['user_date'] = date('Y-m-m h:i:s');
		
		return $this->db->insert('users',$post_array);
	} 	
	
	public function set_password_input_to_empty() {
	    return "<input type='password' name='user_pass' value='' />";
	}	
	public function set_disabled_input($value) {
	    return "<input type='text' name='id' disabled = 'disabled' value='" . $value . "' />";
	}		

	function user_type_manager() {
		//check access, only admin
		$this->access->Allow(ADMIN);		

		$this->crud->set_table('user_type');
		$this->crud->columns('id', 'type_name');

		$output = $this->crud->render();

		$this->_example_output($output);
	}

	function ring_size_manager() {
		$this->crud->set_table('size');
		$this->crud->set_subject(lang('size'));
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('size_uk', lang('size_uk'));
		$this->crud->display_as('size_eu', lang('size_eu'));
		$this->crud->display_as('size_usa', lang('size_usa'));
		$this->crud->display_as('size_japan', lang('size_japan'));
		$this->crud->display_as('gender', lang('gender'));		
		$this->crud->display_as('name_admin', lang('name_admin'));
		//$this->crud->columns('size_id', 'size_name', 'price');

		$output = $this->crud->render();

		$this->_example_output($output);
	}

	function category_manager() {
		$this->crud->set_table('category');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('parent_id', lang('parent_id'));
		$this->crud->display_as('name', lang('name'));
		$this->crud->display_as('related_category', lang('related_category'));
		$this->crud->display_as('display', lang('display'));
		$this->crud->display_as('promotion_value', lang('promotion_value'));
		$this->crud->set_subject(lang('category'));
		
		$this->crud->order_by('category.name','asc');
		
		$this->crud->add_fields('parent_id', 'language_id', 'name', 'order','related_category','display','promotion_value');
    	$this->crud->edit_fields('parent_id','language_id', 'name', 'order','related_category','display','promotion_value');			
		
    	$this->crud->add_action(lang('translate'), IMAGES_URL . 'admin/translate.png', 'admin/translate/category');
		
		$this->crud->set_relation('parent_id','category','name');
		$this->crud->set_relation('related_category','category','name','language_id = ' . $this->config->item('lang_obj')->id);
		$this->crud->set_relation('language_id','languages','name');
		
		$this->crud->callback_edit_field('related_category',array($this,'get_category_indent'));
		$this->crud->callback_add_field('related_category',array($this,'get_category_indent'));
		
		$this->crud->callback_edit_field('parent_id',array($this,'get_category_indent'));
		$this->crud->callback_add_field('parent_id',array($this,'get_category_indent'));
		
		$this->crud->columns('id', 'name', 'parent_id', 'language_id', 'order','related_category');

		$output = $this->crud->render();

		$this->_example_output($output);
	}

	function get_category_indent($value,$key){
		$this->load->model('category_model');
		$parent_categories = $this->category_model->getByParent(0);
		
		$html = '<select name="related_category"><option value="">' . lang('choose_category') . '</option>';
		$indent = "&nbsp;&nbsp;&nbsp;";
		foreach ($parent_categories as $category){
			$html .= '<option value="' . $category->id . '" ' . ($value == $category->id ? "selected='selected'" : "") . '>' . $category->name . "</option>";
			$html .= $this->getChilds($category->id,$indent,$value);
		}
		$html .= '</select>';
		return $html;
	}
	
	function getChilds($parentId,$indent,$value){
		$categories = $this->category_model->getByParent($parentId);
		
		$return = '';
		foreach ($categories as $category){
			$return .= '<option value="' . $category->id . '" ' . ($value == $category->id ? "selected='selected'" : "") . '>' . $indent . $category->name . "</option>";
			$return .= $this->getChilds($category->id,$indent . "&nbsp;&nbsp;&nbsp;",$value);
		}
		return $return;
	}
	
	function translate($record , $id)
	{
		$redirect = 'admin';
		
		switch ($record) {
			case 'category':
				$this->load->model('category_model');
				$translatedObj = $this->category_model->get_by_id($id)->cloneMe();
				$translatedObj->original_id = $id;
				$translatedObj->fields['original_id'] = $id;
				$translatedId = $translatedObj->insert();
			    $redirect = 'admin/category_manager/edit/' . $translatedId;				
				break;
			case 'product':
				$this->load->model('product_model');
				$translatedId = $this->product_model->get_by_id($id)->cloneMe()->insert();
			    $redirect = 'admin/product_manager/edit/' . $translatedId;				
				break;
				
		}
		redirect(site_url($redirect));

	}
 


	function product_manager() {
		$this->crud->set_table('products');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('language_id', lang('language_id'));
		$this->crud->display_as('status', lang('status'));
		$this->crud->display_as('name', lang('name'));
		$this->crud->display_as('sku', lang('sku'));
		$this->crud->display_as('parent_id', lang('parent_id'));
		$this->crud->display_as('attribute_set', lang('attribute_set'));
		$this->crud->display_as('image', lang('image'));
		$this->crud->display_as('small_image', lang('small_image'));
		$this->crud->display_as('thumbnail', lang('thumbnail'));
		$this->crud->display_as('url_key', lang('url_key'));
		$this->crud->display_as('url_path', lang('url_path'));
		$this->crud->display_as('flash_file_1', lang('flash_file_1'));
		$this->crud->display_as('flash_file_2', lang('flash_file_2'));
		$this->crud->display_as('ring_band_width', lang('ring_band_width'));
		$this->crud->display_as('diamond_size_text', lang('diamond_size_text'));
		$this->crud->display_as('delivery_date', lang('delivery_date'));
		$this->crud->display_as('root_delivery_time', lang('root_delivery_time'));
		$this->crud->display_as('price', lang('price'));
		$this->crud->display_as('special_price', lang('special_price'));
		$this->crud->display_as('carat_weight', lang('carat_weight'));
		$this->crud->display_as('colour', lang('colour'));
		$this->crud->display_as('metal', lang('metal'));
		$this->crud->display_as('shape', lang('shape'));
		$this->crud->display_as('setting', lang('setting'));
		$this->crud->display_as('certified', lang('certified'));
		$this->crud->display_as('contains_sale_item', lang('contains_sale_item'));
		$this->crud->display_as('product_type', lang('product_type'));
		$this->crud->display_as('description', lang('description'));
		$this->crud->display_as('short_description', lang('short_description'));
		$this->crud->display_as('is_in_stock', lang('is_in_stock'));
		$this->crud->display_as('certified', lang('certified'));
		$this->crud->display_as('low_stock_date', lang('low_stock_date'));
		$this->crud->display_as('product_name', lang('product_name'));
		$this->crud->display_as('weight', lang('weight'));
		$this->crud->display_as('clarity', lang('clarity'));
		$this->crud->display_as('search_width', lang('search_width'));
		$this->crud->display_as('promotion', lang('promotion'));
		$this->crud->display_as('promotion_value', lang('promotion_value'));
		$this->crud->display_as('categories', lang('categories'));
		$this->crud->display_as('large_image', lang('large_image'));
		$this->crud->display_as('sizes', lang('sizes'));
		
		//if the logged in user is an agent I have to filter the results by his language
		if (!$this->access->isRole(ADMIN)) {
			$this->crud->where('products.language_id', $this->access->getUserLang());
		}

		$this->crud->set_subject(lang('product'));
		
		$this->crud->order_by('products.sku','asc');
				
		$this->crud->set_relation('language_id','languages','name');	
		$this->crud->set_relation('parent_id','products','sku','products.parent_id = 0 AND products.language_id=' .  $this->config->item('def_language_id'));	

		$this->crud->add_action(lang('translate'), IMAGES_URL . 'admin/translate.png', 'admin/translate/product');

		$this->crud->set_relation_n_n('categories', 'product_category_mn', 'category', 'local_id', 'foreign_id', 'name');
		$this->crud->set_relation_n_n('sizes', 'product_size_mn', 'size', 'local_id', 'foreign_id', 'name_admin');
	
		$this->crud->change_field_type('status', 'true_false');

		// unset columns from main view
		$this->crud->columns('sku', 'name', 'language_id');
		
		$this->crud->unset_fields('sync', 'sync_date', 'sync_fields', 'marked_deletion', 'imported');
		
		$this->crud->callback_edit_field('image',array($this,'edit_field_image'));
		$this->crud->callback_edit_field('large_image',array($this,'edit_field_large_image'));
		
		$this->crud->unset_texteditor('image', 'small_image', 'thumbnail', 'url_key', 'url_path', 'large_image');
		
		//$this->crud->set_field_upload('image', NORMAL_IMAGE_PATH);
		
		//$this->crud->set_field_upload('small_image', NORMAL_IMAGE_PATH);
		
		//$this->crud->set_field_upload('thumbnail', NORMAL_IMAGE_PATH);
		
		//$this->crud->set_field_upload('large_image', LARGE_IMAGE_PATH);
		
		$this->crud->set_field_upload('flash_file_1', FLASH_IMAGE_PATH);
		$this->crud->set_field_upload('flash_file_2', FLASH_IMAGE_PATH);

		$output = $this->crud->render();

		$this->_example_output($output);
	}
	
	function edit_field_image($value, $primary_key)
	{
		return '<a class="gallery" data-fancybox-type="iframe" href="' . site_url('admin/image/' . $primary_key) . '">' . lang('manage_gallery') . '</a>';
	}

	function edit_field_large_image($value, $primary_key)
	{
		return '<a class="gallery" data-fancybox-type="iframe" href="' . site_url('admin/large_image/' . $primary_key) . '">' . lang('manage_gallery') . '</a>';
	}		
	
	/*image galleries*/
	function image() {
		$this->load->library('Image_CRUD');
		$image_crud = new Image_CRUD();
	
		$image_crud->set_primary_key_field('id');
		$image_crud->set_url_field('url');
		$image_crud->set_table('images')
		->set_relation_field('product_id')
		->set_ordering_field('sort')
		->set_image_path('application/assets/catalog/normal');
			
		$output = $image_crud->render();
				
		$this->load->view('admin/images.php',$output);	
	}

	function large_image() {
		$this->load->library('Image_CRUD');
		$image_crud = new Image_CRUD();
	
		$image_crud->set_primary_key_field('id');
		$image_crud->set_url_field('url');
		$image_crud->set_table('large_images')
		->set_relation_field('product_id')
		->set_ordering_field('sort')
		->set_image_path('application/assets/catalog/large');
			
		$output = $image_crud->render();
		
		$this->load->view('admin/images.php',$output);	
	}	
	/*image galleries end*/
	
	
	function synced_products() {
		$this->crud->set_table('products');
		
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('language_id', lang('language_id'));
		$this->crud->display_as('status', lang('status'));
		$this->crud->display_as('name', lang('name'));
		$this->crud->display_as('sku', lang('sku'));
		$this->crud->display_as('parent_id', lang('parent_id'));
		$this->crud->display_as('attribute_set', lang('attribute_set'));
		$this->crud->display_as('image', lang('image'));
		$this->crud->display_as('small_image', lang('small_image'));
		$this->crud->display_as('thumbnail', lang('thumbnail'));
		$this->crud->display_as('url_key', lang('url_key'));
		$this->crud->display_as('url_path', lang('url_path'));
		$this->crud->display_as('flash_file_1', lang('flash_file_1'));
		$this->crud->display_as('flash_file_2', lang('flash_file_2'));
		$this->crud->display_as('ring_band_width', lang('ring_band_width'));
		$this->crud->display_as('diamond_size_text', lang('diamond_size_text'));
		$this->crud->display_as('delivery_date', lang('delivery_date'));
		$this->crud->display_as('root_delivery_time', lang('root_delivery_time'));
		$this->crud->display_as('price', lang('price'));
		$this->crud->display_as('special_price', lang('special_price'));
		$this->crud->display_as('carat_weight', lang('carat_weight'));
		$this->crud->display_as('colour', lang('colour'));
		$this->crud->display_as('metal', lang('metal'));
		$this->crud->display_as('shape', lang('shape'));
		$this->crud->display_as('setting', lang('setting'));
		$this->crud->display_as('certified', lang('certified'));
		$this->crud->display_as('contains_sale_item', lang('contains_sale_item'));
		$this->crud->display_as('product_type', lang('product_type'));
		$this->crud->display_as('description', lang('description'));
		$this->crud->display_as('short_description', lang('short_description'));
		$this->crud->display_as('is_in_stock', lang('is_in_stock'));
		$this->crud->display_as('certified', lang('certified'));
		$this->crud->display_as('low_stock_date', lang('low_stock_date'));
		$this->crud->display_as('product_name', lang('product_name'));
		$this->crud->display_as('weight', lang('weight'));
		$this->crud->display_as('clarity', lang('clarity'));
		$this->crud->display_as('search_width', lang('search_width'));
		$this->crud->display_as('promotion', lang('promotion'));
		$this->crud->display_as('categories', lang('categories'));
		$this->crud->display_as('large_image', lang('large_image'));
		$this->crud->display_as('sync', lang('sync'));
		$this->crud->display_as('sync_date', lang('sync_date'));
		$this->crud->display_as('sync_fields', lang('sync_fields'));
		
		//if the logged in user is an agent I have to filter the results by his language
		if (!$this->access->isRole(ADMIN)) {
			$this->crud->where('products.language_id', $this->access->getUserLang());
		}
		$this->crud->where('products.sync', 1);
		$this->crud->set_subject(lang('product'));
		
		$this->crud->order_by('products.sku','asc');
				
		$this->crud->set_relation('language_id','languages','name');	
		//$this->crud->set_relation('parent_id','products','sku','products.parent_id = 0 AND products.language_id=' .  $this->config->item('def_language_id'));	

		$this->crud->add_action(lang('translate'), IMAGES_URL . 'admin/translate.png', 'admin/translate/product');

		$this->crud->set_relation_n_n('categories', 'product_category_mn', 'category', 'local_id', 'foreign_id', 'name');

		$this->crud->change_field_type('status', 'true_false');
		$this->crud->change_field_type('sync_date', 'string');

		// unset columns from main view
		$this->crud->columns('sku', 'language_id', 'sync_date', 'sync_fields');
		
		$this->crud->unset_fields('sync_date', 'sync_fields', 'marked_deletion', 'imported', 'parent_id');
		$this->crud->unset_add();
		
		$this->crud->unset_texteditor('image', 'small_image', 'thumbnail', 'url_key', 'url_path', 'large_image');
		
		$this->crud->callback_edit_field('image',array($this,'edit_field_image'));
		$this->crud->callback_edit_field('large_image',array($this,'edit_field_large_image'));
		
		//$this->crud->set_field_upload('image', NORMAL_IMAGE_PATH);
		
		//$this->crud->set_field_upload('small_image', NORMAL_IMAGE_PATH);
		
		//$this->crud->set_field_upload('thumbnail', NORMAL_IMAGE_PATH);
		
		//$this->crud->set_field_upload('large_image', LARGE_IMAGE_PATH);
		
		$this->crud->set_field_upload('flash_file_1', FLASH_IMAGE_PATH);
		$this->crud->set_field_upload('flash_file_2', FLASH_IMAGE_PATH);
		
		$this->crud->callback_column('sync_fields',array($this,'_callback_sync_fields'));

		$output = $this->crud->render();

		$this->_example_output($output);
	}	
	
	public function _callback_sync_fields($value, $row)
	{
		$synced_values = array();
		foreach (unserialize($value) as $field) {
			$synced_values[] = lang($field);	
		}
	  	return implode(';', $synced_values);
	}	

	
	public function logout()
	{
		$this->simpleloginsecure->logout();
		redirect(base_url('admin/login'));
	}

	protected function _handle_post($type)
	{
		if ($this->form_validation->run($type) == FALSE)
		{
			return;
		}

		$data = $this->form_validation->get_validated_data();

		switch ($type)
		{
			case 'admin_login':
				if( $this->simpleloginsecure->login($data['user_email'], $data['user_password']) === TRUE)
				{
					$this->access->setUser($this->session->userdata ( 'user' ));
					$lang = $this->languages_model->get_by_id($this->access->getUserLang());
					redirect(base_url('/' . $lang->key . '/admin/synced_products'));
				}
				else
				{
					$this->data['error'] = 1;
				}
				break;
		}
	}
	
	public function country_management() {
		$this->crud->set_table('countries');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('name', lang('name'));
		$this->crud->display_as('vat', lang('vat'));
		$this->crud->display_as('flag', lang('flag'));
		$this->crud->display_as('price_gap', lang('price_gap'));
		$this->crud->display_as('language_id', lang('language_id'));
		$this->crud->display_as('currency_id', lang('currency_id'));
		$this->crud->set_subject(lang('country'));
		
		$this->crud->order_by('countries.name','asc');
		$this->crud->set_relation('language_id','languages','name');
		$this->crud->set_relation('currency_id','currencies','name');
		$this->crud->set_field_upload('flag', IMAGES_PATH . 'flags/');


		$output = $this->crud->render();

		$this->_example_output($output);		
	}
	
	public function currency_management() {
		$this->crud->set_table('currencies');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('name', lang('name'));
		$this->crud->set_subject(lang('currency'));
		
		$this->crud->order_by('currencies.name','asc');


		$output = $this->crud->render();

		$this->_example_output($output);		
	}

	public function exchange_management() {
		$this->crud->set_table('exchange_rates');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('currency', lang('currency'));
		$this->crud->display_as('value', lang('value'));
		$this->crud->display_as('date', lang('date'));
		$this->crud->set_subject(lang('exchange_rate'));
		
		$this->crud->unset_add();
		
		$this->crud->set_relation('currency','currencies','name');
		
		$this->crud->order_by('exchange_rates.date','asc');


		$output = $this->crud->render();

		$this->_example_output($output);		
	}		
	function send_ro_email($primary_key , $row)
	{
		return '<a class="gallery" data-fancybox-type="iframe" href="'. site_url('admin/send_email_1/') . $primary_key.'" >' . lang('send_ro_email') . '</a>';
	}

	
public function getOrders() {
		$this->load->model('country_model');
		$this->crud->set_table('orders');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('data_add', lang('date'));
		$this->crud->display_as('order_type', lang('order_type'));
		$this->crud->display_as('advance_of_maney', lang('advance_of_maney'));
		$this->crud->display_as('status', lang('status'));
		$this->crud->display_as('billing_id', lang('billing_info'));
		$this->crud->display_as('shipping_id', lang('shipping_info'));
		$this->crud->display_as('shipping_method', lang('shipping_method'));
		$this->crud->display_as('track_code', lang('track_code'));
		$this->crud->display_as('due_date', lang('due_date'));
		
		if (!$this->access->isRole(ADMIN)) {
			$countrie = $this->country_model->get_by_params(array('language_id' => $this->access->getUserLang()))->result();
			if (count($countrie)){
				$this->crud->where('orders.country_id',  $countrie[0]->id); 
			}
			$this->crud->where('language', $this->access->getUserLang());
		}
		$this->crud->order_by('id','desc');
		// unset columns from main view
		$this->crud->unset_columns('products','user_id', 'discount');
		$this->crud->set_relation('billing_id','order_address',' {first_name} {first_name}, {city} {zipp_code} {tel_number}');
		$this->crud->set_relation('shipping_id','order_address',' {first_name} {first_name}, {city} {zipp_code} {tel_number}');
		$this->crud->set_relation('shipping_method','curier',' {name}');
		
		$this->crud->columns('id', 'data_add', 'order_type', 'status', 'billing_id', 'shipping_id', 'shipping_method', 'advance_of_maney', 'due_date');
		
		$this->crud->set_subject(lang('orders'));
		$this->crud->unset_add();		
		
		$this->crud->edit_fields('status', 'track_code');
		
		
		$this->crud->callback_edit_field('status', array($this, 'status_enum'));
		$this->crud->callback_edit_field('track_code', array($this, 'track_code_input'));
		
		
		$this->crud->callback_column('status',array($this,'callback_status_array'));
		$this->crud->callback_column('order_type',array($this,'callback_order_type_array'));
		$this->crud->callback_column('advance_of_maney',array($this,'invoice_email_link'));
		$this->crud->callback_column('due_date',array($this,'due_time_link'));
		
		$this->crud->callback_after_update(array($this,'update_after_callback_orders'));
		
		/*$this->crud->add_action(lang('edit_due_time'), ' ', 'admin/due_time_link','');
		/*$this->crud->add_action(lang('send_valutation_document'), ' ', 'admin/send_email_valutation');*/
		
		$output = $this->crud->render();
	
		$this->_example_output($output);
	}
	
	function due_time_link($post_array, $id){
		$lang = $this->languages_model->get_by_id($this->access->getUserLang());
		return '<a href="#" onclick="JacaScript:showDue('.$id->id.', \''.$id->due_date.'\',\''.$lang->key.'\')">'.lang('edit_due_date').'</a>' ;
	}
	
	function send_to_factory($id, $isRate){
		$this->send_email_valutation($id, $this->config->item('factory_email_address'), false);
		$this->invoice_email($id, $isRate, $this->config->item('factory_email_address'));
	}
	
	function send_admin_emails($id, $isRate){
		$this->invoice_email($id, $isRate, $this->config->item('sellers_email_address'));
		$this->send_email_1($id);
	}
	
	function track_code_input($val, $primary_key) {
		$search_criteria = array('id' => $primary_key);
		$result = $this->db->get_where('orders', $search_criteria)->row_array();
		if ($result['status'] == '3' && empty($result['track_code']) ){
			return '<input id="trec_code_inpout" name ="track_code" type="text" value="" / >';
		} else {
			return '<input id="trec_code_inpout" name ="track_code"  style="display:none" type="text" value="'.$result['track_code'].'" / >';
		}
	}
	
	
	function update_after_callback_orders($post_array, $id) {
		$this->load->model('affiliate_model');
		
		$search_criteria = array('id' => $id);
		$result = $this->db->get_where('orders', $search_criteria)->row_array();

		if ($result['status'] == '2'/* && $result['confirmed'] == 0*/){
			$search_criteria1 = array('id' => $result['user_id']);
			$result1 = $this->db->get_where('fe_users', $search_criteria1)->row_array();
			
			if(($result['advance_of_maney'] < 100 && $result['advance_of_maney'] != 0)|| ($result['advance_of_maney'] > 0 && $result['advance_of_maney'] != 100)){
				$this->invoice_email($result['id'], 1, $result1['user_email']);
				$isRate = true;
			} else {
				$isRate = false;
				$this->invoice_email($result['id'], 0, $result1['user_email']);
			}

			$this->send_email_valutation($id, $result1['user_email'], true);
			$this->send_to_factory($id, $isRate);
			$this->send_admin_emails($id, $isRate);
		//	$this->db->update('orders',array('confirmed' => 1), array('id'=>$id ));
		}
		if ($result['status'] == '4' && !empty($result['affiliate_id'])){
			$products = json_decode($result['products']); 
			$affiliateObj = $this->affiliate_model->get_by_id($result['affiliate_id']);
			if ($affiliateObj->id == $result['affiliate_id']){
				$affiliateObj->count = (int)$affiliateObj->count+1;
				$affiliateObj->price = (int)$affiliateObj->price+ $products->total;
				$affiliateObj->update();
			}
		}
	}
	function callback_status_array($value = '', $primary_key = null ){
		$status = array("1"=>lang('processing'),
						"2"=>lang('producing') ,
						"3"=>lang('delivered'),
						"4"=>lang('closed'),
						"5"=>lang('canceled')

				);
		return $status[$value];
	}
	
	function callback_order_type_array($value = '', $row = null ){
		$order_type = array("1"=>lang('bank_transfer'),
							"0"=>lang('credit_card') 
		);
		return $order_type[$value];
	}
	
	
	
	function status_enum($value = '', $primary_key = null)
	{
		if ($value == '1' or $value == '')
		{
			return '<select name="status" style="height:30px" onchange="JavaScript:(this.value == 3)?$(\'#trec_code_inpout\').show():$(\'#trec_code_inpout\').hide()">
			<option value="1" selected>'.lang('processing').'</option>
			<option value="2">'.lang('producing').'</option>
			<option value="3">'.lang('delivered').'</option>
			<option value="4" >'.lang('closed').'</option>
			<option value="5" >'.lang('canceled').'</option>
			</select>';
		}
		elseif ($value == '2')
		{
			return '<select name="status" style="height:30px" onchange="JavaScript:(this.value == 3)?$(\'#trec_code_inpout\').show():$(\'#trec_code_inpout\').hide()">
			<option value="1">'.lang('processing').'</option>
			<option value="2" selected>'.lang('producing').'</option>
			<option value="3">'.lang('delivered').'</option>
			<option value="4" >'.lang('closed').'</option>
			<option value="5" >'.lang('canceled').'</option>
			</select>';
		}elseif ($value == '3')
		{
			return '<select name="status" style="height:30px" onchange="JavaScript:(this.value == 3)?$(\'#trec_code_inpout\').show():$(\'#trec_code_inpout\').hide()">
			<option value="1">'.lang('processing').'</option>
			<option value="2">'.lang('producing').'</option>
			<option value="3" selected>'.lang('delivered').'</option>
			<option value="4" >'.lang('closed').'</option>
			<option value="5" >'.lang('canceled').'</option>
			</select>';
		}elseif ($value == '4')
		{
			return '<select name="status"style="height:30px" onchange="JavaScript:(this.value == 3)?$(\'#trec_code_inpout\').show():$(\'#trec_code_inpout\').hide()">
			<option value="1">'.lang('processing').'</option>
			<option value="2">'.lang('producing').'</option>
			<option value="3" >'.lang('delivered').'</option>
			<option value="4" selected>'.lang('closed').'</option>
			<option value="5" >'.lang('canceled').'</option>
			</select>';
		}elseif ($value == '5')
		{
			return '<select name="status" style="height:30px" onchange="JavaScript:(this.value == 3)?$(\'#trec_code_inpout\').show():$(\'#trec_code_inpout\').hide()">
			<option value="1">'.lang('processing').'</option>
			<option value="2">'.lang('producing').'</option>
			<option value="3" >'.lang('delivered').'</option>
			<option value="4" >'.lang('closed').'</option>
			<option value="5" selected>'.lang('canceled').'</option>
			</select>';
		}
		
	}
	function invoice_email_link($primary_key , $row){
			$acction ='';
			if(($primary_key < 100 && $primary_key != 0)|| ($primary_key > 0 && $primary_key != 100)){
				$acction .= //'<a href="'. site_url('admin/invoice_email/'.$row->id.'/1').'">'.lang('send_invoice_rate_1').'</a>'.
							'<a href="'. site_url('admin/invoice_email/'.$row->id.'/2').'">'.lang('send_invoice_rate_2').'</a>';
			} else {
				$acction .= lang('all_invoice_email_sent');
			}
			return $acction;
	}

	public function invoice_email($id, $rate = false, $email) {
		$this->load->model('fe_user_model');
		$this->load->model('orders_model');
		$this->load->model('product_model');
		$this->load->library('parser');
		$this->load->library('exchange');
		
		//$currency =  ($this->session->userdata('selected_currency') !== FALSE) ? $this->session->userdata('selected_currency') :  $this->config->item('def_currency');
		$this->load->model('currency_model');
		
		$order = $this->orders_model->getAllOrders($id);
		$countries = $this->country_model->get_by_params(array('language_id' => $order[0]->language))->result();
		if ($countries[0]->currency_id){
			$currency = $this->currency_model->get_by_id($countries[0]->currency_id)->name;
		}
		
		$user = $this->fe_user_model->get_by_id($order[0]->user_id);
		$allProducts = json_decode($order[0]->products);
		$total = $allProducts->total;
		if ($rate == 1 ){
			$total = $total* $order[0]->advance_of_maney/100 ;
		} elseif ($rate == 2){
			$total = $total - ($total* $order[0]->advance_of_maney/100);
		}
		
		$data = array();
		$data['company_name'] = lang('company_name');
		$data['company_address'] = lang('company_address');
		$data['company_country'] = lang('company_country');
		$data['company_data'] = lang('company_data');
		$data['invoice_lang'] = lang('invoice');
		$data['company_vat_reg_lang'] = lang('company_vat_reg_lang');
		$data['company_vat_reg_value'] = '?';
		$data['date_lang'] = lang('date');
		$data['date'] = $order[0]->data_add;
		$data['invoice_no_lang'] = lang('invoice_number');
		$data['invoice_no'] = '#' .$id;
		$data['invoice_to'] = lang('invoice_to');
		$data['billing_address'] = $order[0]->b_first_name .' '. $order[0]->b_last_name. ', <br/>'. $order[0]->b_country . ' ' . $order[0]->b_city . ' ' .$order[0]->b_address ;
		$data['ship_to'] = lang('ship_to');
		$data['shipping_address'] = $order[0]->s_first_name .' '. $order[0]->s_last_name. ', <br/>'. $order[0]->s_country . ' ' . $order[0]->s_city . ' ' .$order[0]->s_address ;
		$data['order_number_text'] = lang('order_number');
		$data['order_number'] = '#' .$id;
		$data['item_text'] = lang('item');
		$data['description_text'] = lang('description');
		$data['amaount_text'] = lang('amaoun');
		$data['vat_text'] = lang('vat');
		$data['products'] = '';
		foreach ($allProducts->content as $item) {
			$string = '<tr style="border-bottom:1px solid #000000; heigth:10px">';
			$product = $this->product_model->get_by_id($item->id);
			$string .= "<td>{$product->sku}</td>" ;
			$string .= "<td> ".lang('size')." {$item->options->ring_size}</td>";
			$string .= "<td> {$item->qty}</td>";
			$string .= "<td> {$this->exchange->transformPrice($item->price , $currency, true, 0, false, $order[0]->country_id, $product->promotion_value, ($order[0]->natural_person)? false : true)} $currency</td>";
			$string .= "<td> ". (($order[0]->natural_person)? $order[0]->b_country_vat : 0 ) . " %</td>";
			$string .= '</tr>';
			$data['products'] .= $string;
		}
		$data['rate'] = lang('rate');
		
		$data['currency'] = $currency;
		$data['vat'] = lang('vat');
		$data['net'] = lang('net');
		$data['rate_procent'] = $order[0]->advance_of_maney ;
		$data['vat_number'] = ($order[0]->natural_person)? $order[0]->b_country_vat : 0  . ' %';
		$data['qty_text'] = lang('qty');
		$data['total'] = lang('total');
		$data['rate_price'] =($order[0]->natural_person)? $order[0]->b_country_vat : 0  . ' %';
		$data['total_price'] = $this->exchange->transformPrice($total ,$currency, true, 0, false, $order[0]->b_country_id, $product->promotion_value, ($order[0]->natural_person)? false : true) . " $currency" ;
		$data['subtotal'] = lang('subtotal');
		$data['vat_total'] =  lang('vat_total');
		$data['balance_due'] = lang('balance_due');
		$data['subtotal_price'] = $this->exchange->transformPrice($total , $currency, true, 0, false, $order[0]->b_country_id, $product->promotion_value, ($order[0]->natural_person)? false : true) .  " $currency";
		$data['vat_total_summ'] =  ($order[0]->natural_person)? $order[0]->b_country_vat : 0 . ' %';
		$data['invoice_footer_text_lang'] = lang('invoice_footer_text');
		
		$htmlMessage =  $this->parser->parse('templates/email/invoice', $data, true);
	
	/*	$this->load->library('pdf');
		$this->pdf->load_html($htmlMessage);
		$this->pdf->render();
		$pdf = $this->pdf->output();
		$pdf_name = $id.'_'.time().'.pdf';
		file_put_contents(ASSETS_PATH.'pdf/invoice/'.$pdf_name, $pdf);
		*/
		/*$config = array();
		$config['protocol']  = 'smtp';
		$config['smtp_host'] = 'ssl://smtp.googlemail.com';
		$config['smtp_port'] = '465';
		$config['smtp_timeout'] = '30';
		$config['smtp_user'] = 'ist.gombos@gmail.com';
		$config['smtp_pass'] = '1988.10.13';
		$config['charset']  = 'utf-8';
		$config['newline']  = "\r\n";
		$config['mailtype']  = "html";*/
		$this->load->library('email');
		//$this->load->library('email', $config);
		$this->email->initialize(array('mailtype' => 'html', 'protocol' => 'sendmail'));
		
		$this->email->from($this->config->item('contact_email_address'), $this->config->item('office_name') );
		$this->email->to($email);
		$this->email->mailtype = 'html';
		$this->email->subject(lang('invoice'));
		$this->email->message($htmlMessage);
		
		/*
		$this->load->library('email', $config);
		$this->email->from('no-repy@royalbijuterii.com', 'royalbijuterii');
		$this->email->to($user->user_email);
		$this->email->subject(lang('invoice'));
		$this->email->message($htmlMessage);*/
		
		if ($this->email->send()){
			//$this->getOrders();
		}else{
			show_error($this->email->print_debugger());
			}
		}
	
	function send_email_valutation($id, $emails, $isBackground){
		$this->load->model('orders_model');
		$this->load->model('product_model');
		$this->load->model('fe_user_model');
		$this->load->library('parser');
		$this->load->library('exchange');
		$this->load->library('pdf');
		$this->load->model('currency_model');
		
		$order = $this->orders_model->getAllOrders($id);
		$user = $this->fe_user_model->get_by_id($order[0]->user_id);
		$allProducts = json_decode($order[0]->products);

		
		$countries = $this->country_model->get_by_params(array('language_id' => $order[0]->language))->result();
		if ($countries[0]->currency_id){
			$currency = $this->currency_model->get_by_id($countries[0]->currency_id)->name;
		}
		$data['content'] = "";
		$i= 1;
		foreach ($allProducts->content as $item) {
			$product = $this->product_model->get_by_id($item->id);
			$data['content'] .='<tr style="border:none">
			<td  style="border:none">
			<img src="'.ASSETS_URL . 'catalog/small/' . $item->options->imageUrl .'"/>
			</td>
			<td  style="vertical-align:middle;">
			<div style="border:1px #a1a1a0 solid;margin:5px; padding: 10px;"><p><u>'.lang	('item'). '&nbsp' . $i.'.'.$product->sku.'</u>
			</p><p>'.$product->description.'</p></div>
			</td>
			</tr>
			<tr>
			<td colspan="2" style="border:none">
			<strong>'.lang('price'). ' - '.  $this->exchange->transformPrice($product->price ,$currency, true,$product->id, false, false, $product->promotion_value) . $currency.'</strong>
			</td>
			</tr>
			';
			$i++;
		}
			
		$data['address_text'] = lang("address_text").':';
		$data['name_footer'] = lang("name_footer");
		$data['date'] = '';//date('Y-m-d') ;
		$data['name_text'] = lang("name").':';
		$data['document_no'] = lang('order_no') . '#' .$id;
		$data['name'] = $order[0]->s_first_name .' '. $order[0]->s_last_name;
		$data['shipping_address'] = $order[0]->s_country . ' ' . $order[0]->s_city . ' ' .$order[0]->s_address ;
		$data['jeweller_text'] = lang("jeweller_text").":";
		$data['jeweller_name'] = $this->config->item('jeweller_name').":";
		$data['jeweller_address'] = $this->config->item("jeweller_address");
		$data['bg_image'] =  $isBackground ? IMAGES_URL.'valutation_doc_small.jpg': '';
		$data['date_style'] = 'border:none; height:203px;padding-left:203px;';
		
		$htmlMessage =  $this->parser->parse('templates/email/valuation_document', $data, true);
		if ($isBackground){
			$this->load->library('pdf');
			$this->pdf->load_html($htmlMessage);
			$this->pdf->render();
			$pdf = $this->pdf->output();
			$pdf_name = $id.'_'.time().'.pdf';
			file_put_contents(ASSETS_PATH.'pdf/valutations/'.$pdf_name, $pdf);
		}
		
		/*$config = array();
		$config['protocol']  = 'smtp';
		$config['smtp_host'] = 'ssl://smtp.googlemail.com';
		$config['smtp_port'] = '465';
		$config['smtp_timeout'] = '30';
		$config['smtp_user'] = 'ist.gombos@gmail.com';
		$config['smtp_pass'] = '1988.10.13';
		$config['charset']  = 'utf-8';
		$config['newline']  = "\r\n";
		$config['mailtype']  = "html";*/
		$this->load->library('email');
		//$this->load->library('email', $config);
		$this->email->initialize(array('mailtype' => 'html', 'protocol' => 'sendmail'));
		
		$this->email->from($this->config->item('contact_email_address'), $this->config->item('office_name') );
		$this->email->to($emails);
		$this->email->mailtype = 'html';
		if ($isBackground){
			$this->email->attach(ASSETS_PATH.'pdf/valutations/'.$pdf_name);
		}
		$this->email->subject(lang('valutation_document'));
		$this->email->message($htmlMessage);
		
		/*$this->load->library('email', $config);
		$this->email->from('no-repy@royalbijuterii.com', 'royalbijuterii');
		$this->email->to($emails);
		$this->email->subject(lang('valutation_document'));
		$this->email->message($htmlMessage);*/
		
		if ($this->email->send()){
			//$this->getOrders();
		}else{
			show_error($this->email->print_debugger());
			}
		}
	
	function send_email_1($id){
		$this->load->model('orders_model');
		$this->load->model('order_address_model');
		$this->load->model('product_model');
		$this->load->model('fe_user_model');
		$this->load->library('parser');
			
		$order = $this->orders_model->getAllOrders($id);
		$allProducts = json_decode($order[0]->products);
		$user = $this->fe_user_model->get_by_id($order[0]->user_id);
		
		$boddy= '';
		$count= 0;
		foreach ($allProducts->content as $item){
			$count++;
			$product = $this->product_model->get_by_id($item->id);
			$price = $this->exchange->transformPrice($product->price ,'ron', true,$product->id, false, $order[0]->b_country_id);
			$price_fara_tva = $price/( 1 + ($price* $order[0]->b_country_vat/100));
			$boddy .= "<tr>
			<td><strong>$count</strong></td>
			<td align=\"center\">Model: {$product->sku} <br/> dimond size :{$product->diamond_size_text} <br/> ring size :{$item->options->ring_size} <br/></td>
			<td align=\"center\">buc</td>
			<td align=\"center\">{$item->qty}</td>
			<td align=\"center\">{$price_fara_tva}</td>
			<td align=\"center\">{$price}</td>
			<td align=\"center\">{$order[0]->b_country_vat}</td>
			</tr>";
			}
			$priceBig = $this->exchange->transformPrice($allProducts->total ,'ron', true, 0, false, $order[0]->b_country_id);
			$price_fara_tvaBig = $priceBig/( 1 + ($priceBig* $order[0]->b_country_vat/100));
			$data= array();
			$data['email'] = $user->user_email;
			$data['username'] = $user->first_name . ' ' .$user->last_name;
			$data['address'] = $user->city . ' ' .$user->street . ' ' .$user->zip;
			$data['tel'] = $user->tel ;
			$data['current_date'] = date('Y-m-d H:i:s') ;
			$data['vat'] = '10' ;
			$data['body'] = $boddy;
			$data['expir_date'] = 'never';
			$data['preice'] = $priceBig;
			$data['preice_whitout_vat'] = $price_fara_tvaBig;
	
			$htmlMessage =  $this->parser->parse('templates/email/factura', $data, true);
	
			/*$config = array();
			$config['protocol']  = 'smtp';
			$config['smtp_host'] = 'ssl://smtp.googlemail.com';
			$config['smtp_port'] = '465';
			$config['smtp_timeout'] = '30';
			$config['smtp_user'] = 'ist.gombos@gmail.com';
			$config['smtp_pass'] = '1988.10.13';
			$config['charset']  = 'utf-8';
			$config['newline']  = "\r\n";
			$config['mailtype']  = "html";*/
			$this->load->library('email');
			$this->email->initialize(array('mailtype' => 'html', 'protocol' => 'sendmail'));
				
			$this->email->from($this->config->item('contact_email_address'), $this->config->item('office_name') );
			$this->email->to($this->config->item('sellers_email_address'));
			$this->email->mailtype = 'html';
			$this->email->subject(lang('factura'));
			$this->email->message($htmlMessage);
			/*
			$this->load->library('email', $config);
			$this->email->from('no-repy@royalbijuterii.com', 'royalbijuterii');
			$this->email->to($this->config->item('sellers_email_address'));
			$this->email->subject('royalbijuterii');
			$this->email->message($htmlMessage);*/
			if ($this->email->send()){
				//$this->getOrders();
			}else{
				show_error($this->email->print_debugger());
			}
	}
			
	public function opinions() {
		//check access, only admin
		//$this->access->Allow(ADMIN);
	
		$this->crud->set_table('opinions');
		$this->crud->display_as('id', lang('id'));
		$this->crud->display_as('opinion ', lang('opinion'));
		$this->crud->display_as('published', lang('published'));
		$this->crud->display_as('product_id', lang('product_sku'));
	
		if (!$this->access->isRole(ADMIN)) {
			$this->crud->where('opinions.language_id', $this->access->getUserLang());
		}
		$this->crud->order_by('id','desc');
		$this->crud->set_subject(lang('opinions'));
		$this->crud->set_relation('product_id','products','sku');
	
		$this->crud->change_field_type('published', 'true_false');
		$this->crud->change_field_type('opinion', 'readonly');
	
		$this->crud->columns('id', 'product_id', 'published');
		$this->crud->unset_add();
		$this->crud->edit_fields('opinion', 'published');
			
		$output = $this->crud->render();
	
		$this->_example_output($output);
	}
	
	public function discount() {
		//check access, only admin
		//$this->access->Allow(ADMIN);
	
		$this->crud->set_table('discount');
		$this->crud->display_as('id ', lang('id'));
		$this->crud->display_as('code ', lang('code'));
		$this->crud->display_as('status', lang('status'));
		$this->crud->order_by('id','desc');
		$this->crud->set_subject(lang('discount'));
	
		$this->crud->change_field_type('code', 'readonly');
		$this->crud->change_field_type('status', 'true_false');
	
		$this->crud->columns('id', 'code', 'status');
		$this->crud->add_fields('count','procent');
		$this->crud->callback_insert(array($this,'generate_codes'));
		$output = $this->crud->render();
		
		$this->_example_output($output);
	

	}
	
	function generate_codes($post_array) {
		for ($i= 0; $i<$post_array['count']; $i++ ) {
			$characters = 'abcdefghijklmnopqrstuvwxyz';
			$characters .= strtoupper('abcdefghijklmnopqrstuvwxyz');
			$characters .= '0123456789';
			$string = '';
			for ($p = 0; $p < 15; $p++) {
				$string .= $characters[mt_rand(0, strlen($characters))];
			}
			$insertArray = array();
			$insertArray['code'] =  $string;
			$insertArray['percent'] = $post_array['procent'];
			$this->db->insert('discount',$insertArray);
		}
		return true;
	}
	
	function affiliates(){
		$this->crud->set_table('affiliate');
		$this->crud->display_as('id ', lang('id'));
		$this->crud->display_as('count ', lang('count'));
		$this->crud->display_as('name', lang('name'));
		$this->crud->display_as('price', lang('price_sum'));

		$this->crud->display_as('link', lang('link'));
		
		$this->crud->columns('id', 'count', 'name', 'link', 'price');
		
		$this->crud->callback_column('link',array($this,'callback_generate_link'));
		
		$this->crud->set_subject(lang('affiliates'));
		
		$this->crud->edit_fields('name', 'price', 'count');
		$this->crud->add_fields('name');
			
		$output = $this->crud->render();
		
		$this->_example_output($output);
		
	}
	
	function callback_generate_link($link, $id){
 		$search_criteria = array('id' => $this->access->getUserLang());
 		$result = $this->db->get_where('languages', $search_criteria)->row_array();
		return site_url('/'. $result['key'].'/main?affiliate='.base64_encode($id->id));
	}
	
	function save_due_date($id, $date){
		var_dump($id);
		var_dump($date);
		$this->load->model('orders_model');
		$order=$this->orders_model->get_by_id($id);
		$order->due_date = $date;
		$order->update();
		echo "ok";
	}
	
	function get_due_orders(){
		$search_criteria = array('due_date'=> date('Y-m-d'));
		$results = $this->db->get_where('orders', $search_criteria)->result_array();
		$string = '';

		foreach ($results as $result){
			if (empty($string)){
				$string .= ' '.$result['id'];
			}else {
				$string .= ', '. $result['id'];
			}
			
		}
		if (empty($string)){
			echo '-';
		}else {
			echo $string;
		}	
	}
	
	

}